const {
    resolve
} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
const {
    loader
} = require('mini-css-extract-plugin')

//定义nodejs环境变量：决定使用browserslist的哪个环境
process.env.NODE_ENV = 'production'

//服用loader
const commonCssLoader = [
    MiniCssExtractPlugin.loader,
    'css-loader',
    {
        //还需在package.json中定义browserslist
        loader: 'postcss-loader',
        options: {
            ident: 'postcss',
            plugins: () => [require('postcss-preset-env')]
        }
    }
]

module.exports = {
    entry: './src/index.html',
    output: {
        filename: 'js/built.js',
        path: resolve(__dirname, 'build')
    },
    module: {
        rules: [{
            test: /\.css$/,
            use: [...commonCssLoader, ]
        }, {
            test: /\.less$/,
            use: [
                ...commonCssLoader,
                'less-loader',
            ]
        }, {
            test: /\.(jpg|png|gif)/,
            loader: 'url-loader',
            options: {
                limit: 8 * 1024,
                name: '[hash:10].[ext]',
                outputPath: 'imgs',
                esModule: false
            }
        }, {
            test: /\.html$/,
            loader: 'html-loader'
        }, {
            exclude: /\.(html|css|js|less|jpg|png|gif)/,
            loader: 'file-loader',
            options: {
                outputPath: 'media'
            }
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            minify: {
                collapseWhitespace: true,
                removeComments: true
            }
        }),
        new MiniCssExtractPlugin({
            filename: 'css/built.css'
        }),
        new OptimizeCssAssetsWebpackPlugin()
    ],
    mode: 'production'
}